package com.landmark;

import java.io.File;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class RenameDirFilesWithColorCodes extends JPanel {

    public void start() {
        HelperBean helperBean = Util.getHelperBean();
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String folderPath = helperBean.getFolderPath(); // images folder
        String renameExt = helperBean.getFileExt(); // extension to change
        String filePath = helperBean.getFilePath(); // colorcode file
        String convertedImagesFolder = "./output/ConvertedImages/";
        String nonConvertedImages = "./output/NonConvertedImages/";
        try {
            
            Util.createDirectory(convertedImagesFolder);
            Util.createDirectory(nonConvertedImages);
            Util.createOutputFile("RenameFileColor");
            fw = new FileWriter(Util.getHelperBean().getOutputFile());
            fwErrorFile = new FileWriter(Util.getHelperBean().getErrorFile());

            processColorCodes(new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
            try{
            fw.append(e.getMessage());
            fw.flush();
            }catch(Exception e1 ){}
        }

		String[] dir = new java.io.File(folderPath).list();
		java.util.Arrays.sort(dir); 
		File f[] = new File(folderPath).listFiles();
                
		int len1 = dir.length;
                System.out.println(htColorCodes.size());
		int thumbNailCount = 0;
		for (int i=0;i<len1; i++)
		{			
                    String name = f[i].getName();
                    //System.out.println("FileName:"+name);
                    String str = name.substring(0, name.lastIndexOf("_"));
                    //System.out.println("File color name: "+str);
//                        System.out.println(htColorCodes.containsKey(str));
                    String replaceWith = getValue(str);
                    try {
                    if (replaceWith != null && !"".equalsIgnoreCase(replaceWith)) {
                        replaceWith = replaceWith + name.substring(name.lastIndexOf("_"), name.length());
                        //File newFileName = new File(f[i].getParentFile(), replaceWith);
                        File newFileName = new File(f[i].getParentFile(), convertedImagesFolder+replaceWith);
                        boolean stat = f[i].renameTo(newFileName);
                        System.out.println("Moooved:"+stat);
                        
                    } else {
                        fw.append("\n" + f[i].getName());
                        fw.flush();
                        File file = new File(nonConvertedImages+f[i].getName());
                        System.out.println(file.getAbsolutePath());
                        boolean stat = f[i].renameTo(file);
                        System.out.println("MOved : " + stat);
                    }
                    } catch (Exception e) {
                        e.printStackTrace();
                        JOptionPane.showMessageDialog(this, e.getCause());
                    }
		}
		System.out.println( "Total files converted : " + (len1-thumbNailCount));
    }

    private void processColorCodes(File inputFile) throws Exception {
        htColorCodes = new Hashtable<String, String>();
        if (inputFile.exists()) {
            Scanner inputScan = new Scanner(inputFile);

            while (inputScan.hasNext()) {
                String str1 = inputScan.nextLine();
                //System.out.println(str1);
                String[] line = str1.split(",");
                
                int lastInd = line[1].lastIndexOf("_");                
                String colorCode = line[1].substring(0 ,lastInd  );
                //System.out.println("colorCode : " + colorCode);
                String colorDesc = line[0].substring(line[0].indexOf("_")+1, line[0].lastIndexOf("_"));
//                String[] colorDescArr = line[0].split("_");
//                StringBuffer colorDesc = new StringBuffer();
//                int count = 0;
//                boolean first = true;
//                boolean last = false;
//                for (String str : colorDescArr) {
//                    
//                    if (count >= 2 && count < (colorDescArr.length - 1)) {
//                        if( first ){
//                            colorDesc.append(str);
//                            first = false;
//                        } else {
//                            colorDesc.append("_"+str );
//                        }
//                        
//                    }
//                    count++;
//                    if( count == colorDescArr.length -1 ){
//                        last = true;
//                    }
//                }
//                System.out.println("colorDesc : " + colorDesc);
                fw.append("\nColor Code : " + colorCode  );
                fw.flush();
                htColorCodes.put(colorCode, colorDesc);
            }
        }
    }
    
    private String getValue( String aKey ) {
        Enumeration<String> keys = htColorCodes.keys();
        String value = "";
        while( keys.hasMoreElements()) {
            String key = keys.nextElement();
            if( aKey.equalsIgnoreCase(key) ) {                
                value = htColorCodes.get(key);
                break;
            }
        }
        return value;
    } 
    Hashtable<String, String> htColorCodes; 
    FileWriter fw = null;
    FileWriter fwErrorFile = null;

}
